/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var judul = "Tugas Besar 1 Pemrograman Internet";
var userAgent = navigator.userAgent.toLowerCase();
var mac = userAgent.indexOf('mac') != -1;
var re_webkit = /WebKit\/(\d+)/i;
var is_iemac = mac;
var is_safari = is_iemac && re_webkit.exec(userAgent) && Number(RegExp.$1) < 500;
var isUploadVisible = false;


var default_config = {
    'bulan' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    'hari'  : ['Su','Mo','Tu','We','Th','Fr','Sa'],
    'tahun' : 30,
    'idname': 'id_cal'
};

function regexDate(d_date)
{
    var regex = /^\s*(\d{4})\-(\d{1,2})\-(\d{1,2})\s*$/;
     var obj = document.getElementById("message_hidden");
    if(!regex.exec(d_date))
    {       
        return alert('Wrong Regex');
       // return;
    }
    else{
        obj.style.visibility='hidden';
    }
    var hari = Number(RegExp.$3);
    var bulan = Number(RegExp.$2);
    var tahun = Number(RegExp.$1);
    //alert(bulan);
    //alert(tahun);

    //cek tahun
    if(tahun < 100)
        tahun+= (tahun < this.config.tahun ? 2000:1900);
    if(bulan < 1 || bulan >12)
        return alert("Pola Bulan Salah");
    var jumlah_hari = new Date(tahun,bulan, 0);
    if(hari > jumlah_hari.getDate())
    {
        return alert("Hari Salah");
    }
    return new Date(tahun, bulan -1 , hari);

}

function generatePolaDate(d_date)
{
    return (
        (d_date.getFullYear()) + '-' +
        (d_date.getMonth() < 9 ?'0' : '') + (d_date.getMonth() + 1) + '-'
        +(d_date.getDate() < 10?'0' : '') + (d_date.getDate())
      
        );
}

function generateCalendar(tags,config)
{
    if(!config)
    {
        config = default_config;
    }

    //daftarkan ke register global
    if(!window.objectInvokedBaru)
        window.objectInvokedBaru = [];
    window.objectInvokedBaru[window.objectInvokedBaru.length] = this;
    this.index = window.objectInvokedBaru.length -1;
    //masukkan method
    this.cal_show = f_cal_show;
    this.cal_hide = f_cal_hide;
    this.cal_toggle = f_cal_toggle;
    this.cal_update = f_cal_update;
    this.cal_regex = regexDate;
    this.cal_pola_gen = generatePolaDate;
    this.cal_change = f_change_date;
    this.tags = tags;
    this.config = config;
    //tulis dalam html
    //document.write('<img src="images/cal.gif" class="calendar" onclick ="f_cal_toggle();" alt="calendar"');
    document.write('<img src="images/cal.jpg" id="'+this.config.idname+'" class="calendar" onclick ="objectInvokedBaru['+this.index+'].cal_toggle()" alt="calendar"');
    //this.icon_id = document.getElementById('id_cal');
    
    //alert(default_config.hari.length);

}

function f_cal_show(d_date)
{
    //temukan field untuk nama input
    if(!this.tags.inputname)
        alert ("Input Name Tidak Didefinisikan");
    if(this.tags.formname)
    {
        var real_form = document.forms[this.tags.formname];
        if(!real_form)
            alert("Form Tidak Ditemukan");        
        this.inputText = real_form.elements[this.tags.inputname];        
         //this.inputText = document.getElementById(this.tags.inputname);
    }
    else
        this.inputText = document.getElementById(this.tags.inputname);

    if(!this.inputText || !this.inputText.tagName || this.inputText.tagName != 'INPUT')
        alert("Something Wrong");

    //generate html        
    var divname='';
    if(!this.tags.divname){
        divname='calDiv';
    }
    else{
        divname = this.tags.divname;
    }
    this.divname = divname;
    this.divCal =document.getElementById(this.divname);
    if(!this.divCal){
        this.divCal = document.createElement("div");
        this.divCal.id = this.divname;
        document.body.appendChild(this.divCal);        
    }

    //hide all calendar
    //simpan nama calendar
    this.iconName = document.getElementById(this.config.idname);

    if(!this.cal_update())
        return;
    this.divCal.style.visibility = 'visible';
    this.iconName.src = 'images/no_cal.jpg';
    this.iconName.title = 'Close calendar';
    this.is_visible = true;
    
}

function f_cal_hide()
{

}

function f_cal_toggle()
{
    return this.is_visible ? this.cal_hide() : this.cal_show();
}

function resetCalendar(d_date)
{
    d_date.setHours(12, 0, 0, 0);
    d_date.setMinutes(0);
    d_date.setSeconds(0);
    d_date.setMilliseconds(0);
    return d_date;
}
function f_cal_update(d_date)
{
    var d_today = (new Date());
    //alert('d_today: ' + d_today + ', d_selected: ' + d_selected + 'd_firstdat: ' + d_firstday);
    var d_selected = this.inputText.value == '' ?
        resetCalendar(d_today)
    :resetCalendar(this.cal_regex(this.inputText.value));

    //cek tanggal, apakah diselect atau default
    if(!d_date)
        d_date=d_selected;
    else if(typeof(d_date) == 'number')
        d_date = resetCalendar(new Date(d_date));
    else
        //ambil dari string
        d_date = this.cal_regex(resetCalendar(d_date));

    //hari pertama
    var d_firstday = new Date(d_date);
    d_firstday.setDate(1);
    d_firstday.setDate(1 - (7 + d_firstday.getDay()) %7);

    //cek sound
    //alert('d_today: ' + d_today + ', d_selected: ' + d_selected + 'd_firstdat: ' + d_firstday);
    var table_class,isi = '<table class="cal_nav"><tbody><tr>'
    //tampilkan prev year
    + '<td ' + this.cal_change(d_date,-1,'y') + 'title="Previous Year"><img src="images/prev_year.gif" /></td>'
    + '<td ' + this.cal_change(d_date,-1,'m') + 'title="Previous Month"><img src="images/prev_month.gif" /></td><th>'
    + this.config.bulan[d_date.getMonth()] + ' ' +d_date.getFullYear()
    + '</th><td ' + this.cal_change(d_date,1,'m') + 'title="Next Month"><img src="images/next_month.gif" /></td>'
    + '<td ' + this.cal_change(d_date,1,'y') + 'title="Next Year"><img src="images/next_year.gif" /></td>'
    +'</tr></tbody></table><table class="cal_wrapper"><tbody><tr class="cal_header">';
    //menampilkan 7 hari
    for(var i=0;i<7;i++)
        isi+='<th>' + this.config.hari[i%7] + '</th>';
    isi += '</tr>';

    //ini dia, menampilkan semua harinya
    var n_date,n_month,d_current = new Date(d_firstday);
    while(d_current.getMonth() == d_date.getMonth() ||
        d_current.getMonth() == d_firstday.getMonth())
        {
        isi+='<tr class="cal_content">';
        for(var n_wday = 0;n_wday<7;n_wday++){
            table_class = [];
            n_date = d_current.getDate();
            n_month = d_current.getMonth();

            //cek bulan lain
            if(d_current.getMonth() != d_date.getMonth())
                table_class[table_class.length] = 'othermonth';
            //cek akhir minggu
            /*if(d_current.getDay() == 0 || d_current.getDay() == 6)
                table_class[table_class.length] = 'weekend';*/
            //cek hari ini
            if(d_current.valueOf() == d_today.valueOf())
                table_class[table_class.length]='today';
            //selected
            if(d_current.valueOf() == d_selected.valueOf())
                table_class[table_class.length] = 'selected';
            isi+='<td onclick="objectInvokedBaru['+this.index+'].cal_hide('+d_current.valueOf() +')"' + (table_class.length ? ' class="'+table_class.join(' ')+'">' : 'class="common_day">') + n_date + '</td>';
            d_current.setDate(++n_date);
        }
        isi+='</tr>';
    }
    isi+='</tbody></table>';

    //isi ke dalam div
    this.divCal.innerHTML = isi;
    var cal_width = this.divCal.offsetWidth;    
    var cal_height = this.divCal.offsetHeight;
    var cal_top = getPosition(this.iconName, "Top") + this.iconName.offsetHeight;
    var cal_left =  getPosition(this.iconName, "Left") - 2*this.iconName.offsetWidth;
    if(cal_left < 0) cal_left =0;
    //alert(cal_left);
    this.divCal.style.left = cal_left + 'px';
    this.divCal.style.top = cal_top + 'px';

    return true;
}


function getPosition(element,rel)
{
    var n_pos =0,n_offset,el = element;
    while(el){
        n_offset = el["offset" + rel];
        n_pos += n_offset;
        el = el.offsetParent;
    }

    if(is_iemac)
        n_pos += parseInt(document.body[rel.toLowerCase() + 'Margin' ]);
    else if(is_safari)
        n_pos -= n_offset;

    el = element;
    while(el != document.body){
        n_offset = el["scroll" + rel];
        if(n_offset && el.style.overflow == 'scroll')
            n_pos-=n_offset;
        el = el.parentNode;
    }
    return n_pos;
}
function f_change_date(d_date,diff,unit)
{
    var units = (unit == 'y' ? 'FullYear' : 'Month');
    var d_hasil = new Date(d_date);
    d_hasil['set' + units](d_date['get' + units]() + diff);
    if(d_hasil.getDate() != d_date.getDate())
        d_hasil.setDate(0);
    return 'onclick="objectInvokedBaru['+this.index+'].cal_update(' + d_hasil.valueOf() +')"';
}

function f_cal_hide(d_date)
{
    if(d_date){
        this.inputText.value = this.cal_pola_gen(new Date(d_date));
    }

    if(!this.is_visible)
        return;
    this.divCal.style.visibility = 'hidden';
    this.iconName = document.getElementById(this.config.idname);
    this.iconName.src = "images/cal.jpg";
    this.is_visible = false;
}

function changeMessage(obj, message){
    obj.style.visibility = 'visible';
    obj.innerHTML=message;
}

function hiddenMessage(obj){
    obj.style.visibility = 'hidden';
    obj.innerHTML='';
}

function checkName(inputvalue){

    if(!inputvalue){
        inputvalue = document.getElementById("name").value;
    }

    var obj = document.getElementById("name_message");

    if(inputvalue.length < 5){
        changeMessage(obj, 'Nama minimal memiliki panjang 5 karakter')
        return;
    }

    var pattern=/^[a-zA-Z\s]+$/;

    if(!pattern.test(inputvalue)){
        changeMessage(obj, 'Nama hanya mengandung alfabet dan spasi');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkUsername(inputvalue){

    if(!inputvalue){
        inputvalue = document.getElementById("username").value;
    }

    var obj = document.getElementById("username_message");

    if(inputvalue.length < 5){
        changeMessage(obj, 'User Name minimal memiliki panjang 5 karakter');
        return;
    }
    var pattern=/^[a-zA-Z0-9._]+$/;
    if(!pattern.test(inputvalue)){
        changeMessage(obj, 'User Name hanya mengandung huruf, angka, titik, dan garis bawah');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkPassword(inputvalue){

    if(!inputvalue){
        inputvalue = document.getElementById("password").value;
    }

    var obj = document.getElementById("password_message");

    if(inputvalue.length < 6){
        changeMessage(obj, 'Password minimal memiliki panjang 6 karakter');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkRepeatPassword(password, passwordrepeat){

    if(!password){
        password = document.getElementById("password").value;
    }

    if(!passwordrepeat){
        passwordrepeat = document.getElementById("repeatpassword").value;
    }
    
    var obj = document.getElementById("repeatpassword_message");

    if(password != passwordrepeat){
        changeMessage(obj, 'Password yang dimasukkan harus sama');
        return;
    }else{
        hiddenMessage(obj);
    }
}

function checkEmail(inputvalue){

    if(!inputvalue){
        inputvalue = document.getElementById("email").value;
    }

    var obj = document.getElementById("email_message");

    var pattern=/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]/;
    if(!pattern.test(inputvalue)){
        changeMessage(obj, 'E-mail tidak valid');
        return;
    }

    var inputsplit = inputvalue.split("@");
    var emailname = inputsplit[0];
    if(emailname.length < 5){
        changeMessage(obj, 'Akun minimal memiliki panjang 5 karakter');
        return;
    }
    var domainname = inputsplit[1];
    var domainsplit = domainname.split(".");
    if(domainsplit[domainsplit.length-1].length < 2){
        changeMessage(obj, 'Top Level domain minimal memiliki panjang 2 karakter');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkFotoProfil(inputvalue){

    if(!inputvalue){
        inputvalue = document.getElementById("fotoprofil").value;
    }

    var obj = document.getElementById("fotoprofil_message");

    if(inputvalue.indexOf(".") == -1 || inputvalue.indexOf(".") == 0){
        changeMessage(obj, 'Nama file tidak valid');
        return;
    }

    var fotosplit = inputvalue.split(".");
    var pattern=/(jpg|jpeg|png|bmp)$/i;

    if(!pattern.test(fotosplit[fotosplit.length - 1])){
        changeMessage(obj, 'Nama ekstensi tidak valid');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkLokasi(inputvalue){
    
    if(!inputvalue){
        inputvalue = document.getElementById("lokasi").value;
    }

    var obj = document.getElementById("lokasi_message");

    if(inputvalue.length < 5){
        changeMessage(obj, 'Lokasi minimal memiliki panjang 5 karakter');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkUploadFoto(inputvalue){
    if(!inputvalue){
        inputvalue = document.getElementById("uploadfoto").value;
    }

    var obj = document.getElementById("uploadfoto_message");

    if(inputvalue.indexOf(".") == -1 || inputvalue.indexOf(".") == 0){
        changeMessage(obj, 'Nama file tidak valid');
        return;
    }

    var fotosplit = inputvalue.split(".");
    var pattern=/(jpg|jpeg|png|bmp)$/i;
    if(!pattern.test(fotosplit[fotosplit.length - 1])){
        changeMessage(obj, 'Nama ekstensi tidak valid');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkDeskripsi(inputvalue){
    if(!inputvalue){
        inputvalue = document.getElementById("deskripsi").value;
    }

    var obj = document.getElementById("deskripsi_message");

    if(inputvalue.length < 5){
        changeMessage(obj, 'Deskripsi minimal memiliki panjang 5 karakter');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function checkKataKunci(inputvalue){
    if(!inputvalue){
        inputvalue = document.getElementById("katakunci").value;
    }

    var obj = document.getElementById("katakunci_message");

    if(inputvalue.length < 3){
        changeMessage(obj, 'Kata kunci minimal memiliki panjang 3 karakter');
        return;
    }else{
        hiddenMessage(obj);
        return;
    }
}

function showUploadDialog(){
    var doc = document.getElementById('uploadfotohidden');
    var doc2 = document.getElementById('uploadhidden_wrapper');
    if(!isUploadVisible)
        {
            doc.style.visibility = 'visible';
            doc.style.height = document.body.offsetHeight+15+ 'px';
            doc2.style.marginTop = document.body.offsetHeight/4+ 'px';
            doc2.style.marginLeft =  document.body.offsetWidth/4 + 'px';
            isUploadVisible = true;
            /*IE BUG FIX*/
            doc.style.display ='block';
        }
     else{
         doc.style.visibility = 'hidden';
         /* IE BUG FIX */
         doc.style.display ='none';
         isUploadVisible = false;
     }
}
